import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hellow01/model/musicData.dart';
import 'package:hellow01/model/musidEntity.dart';
import 'package:hellow01/modules/music/music_detail_page.dart';
import 'package:hellow01/tools/sqflite/sqflite_bussiness/music_sql_bll.dart';

import '../../Constants/constants.dart';
import 'package:http/http.dart' as http;
//import 'dart:convert' show JSON1;

class MusicListPage  extends  StatefulWidget{
  @override
  _MusicList createState() {
    return _MusicList();
  }
}

class _MusicList extends State<MusicListPage>{
   List<MusicData> songs = new List<MusicData> ();
   MusicSqlBll _sqlDb = new  MusicSqlBll();
   //Dio dio = new Dio();
   String _searchText="";
  _MusicList(){
    //读取本地sqflite全部数据，若无（可能是卸载程序了），则读取本地磁盘，再无，就是无
    _getSqfliteData();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold (
      backgroundColor: Colors.white,
      body:SafeArea(child: Container(
      child:Column(
      children: [
         _searchBar(),
         Expanded(child: ListView.builder(itemBuilder: _itemLayout, itemCount: songs.length))
      ],
    ),)));
  }
  
  //搜索框
  Row _searchBar()
  {
    return Row(children: [
      Container(
        width: Constants.Wh * 130,
        height: Constants.Wh * 140,
        child: FlatButton(
                    onPressed: (){ 
                        //_addMoni();
                       
                        Navigator.pop(context);
                      },
                    padding: EdgeInsets.all(0),
                    child: Image.asset(
                      'assets/images/ima_left_arrow.png',
                      width: Constants.Wh * 18,
                      height: Constants.Hh * 46,
                      fit: BoxFit.fill,
                    )),),
       Expanded(child: TextField(onChanged: (String text){
         setState(() {
           _searchText = text; //文本
         });
       },),),
       Container(
        width: Constants.Wh * 130,
        height: Constants.Wh * 140,
        child: FlatButton(
                    onPressed: (){
                      _searchFunction();
                    },
                    padding: EdgeInsets.all(0),
                    child: Image.asset(
                      'assets/images/ima_search.png',
                      width: Constants.Wh * 60,
                      height: Constants.Hh * 46,
                      fit: BoxFit.fill,
                    )),),
    ],);
  }

  //模拟新增一行数据sql
  _addMoni()async {
    var data = new MusicData('musichaha','music2222',1,'music','.mp3');
    _sqlDb.addSongInfo(data);
  }

  _getSqfliteData()async{
     var ssg = await _sqlDb.getAllSongs();
      List<MusicData> temp = new List<MusicData> ();
      for(int i=0;i<ssg.length;i++){
         var tempItem = new MusicData(ssg[i]['musicName'],ssg[i]['singer'],0,'',ssg[i]['nameExtension']);
          temp.add(tempItem);
      }
      setState((){
          songs.clear();
          temp.sort((a,b)=> b.musicName.compareTo(a.musicName));
          songs.addAll(temp);
      });
  }

  //联网查询歌曲
  _searchFunction()async {
    List<MusicData> temp = new List<MusicData> ();
    Utf8Decoder decod = new  Utf8Decoder();
     //var response = await dio.get("/test",data:{"id":12,"name":"wendu"});
     //var response = await dio.get('http://139.196.170.157:8082/searchfile?fileName=成都');
     var sdg =  await http.get('http://139.196.170.157:8082/searchfile?fileName=$_searchText');
      List<dynamic> scores = jsonDecode(decod.convert(sdg.bodyBytes));
      for(int i=0;i<scores.length;i++){
         var tempItem = new MusicData(scores[i]['musicName'],scores[i]['singer'],0,'',scores[i]['nameExtension']);
          temp.add(tempItem);
      }
      setState((){
          songs.clear();
          temp.sort((a,b)=> b.musicName.compareTo(a.musicName));
          songs.addAll(temp);
      });
  }
  
  //列表行
  Widget _itemLayout(context,index){
    return GestureDetector(child: Row(children: [
       Container(
        width: Constants.Wh * 130,
        height: Constants.Wh * 140,
        child: FlatButton(
                    onPressed: null,
                    padding: EdgeInsets.all(0),
                    child: Image.asset(
                      'assets/images/ima_search.png',
                      width: Constants.Wh * 18,
                      height: Constants.Hh * 46,
                      fit: BoxFit.fill,
                    )),),
       Expanded(child: Text(songs[index].musicName) )
    ],),
    onTap: (){
      //https://www.cnblogs.com/pythonClub/p/10633247.html
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                    var songInfo = new MusicData(songs[index].musicName,songs[index].singer,1,'',songs[index].nameExtension);
                    return  MusicDetailPage(songInfo: songInfo);
                  }));
       //Navigator.of(context).pushNamed('/musicPage');
    },
    );
  }
  
}